var express = require('express');
var connection = require('../db/db_utill');

var router = express.Router();

router.post('/login', function (req, res) {
  //获取表单post数据
  var body = req.body
  connection.query('select * from user_info where username = ?', [body.username], function (error, results, fields) {
    if (error) {
      throw error;
    } else if (results.length) {
      var string = JSON.stringify(results);
      var user_info = JSON.parse(string)[0];
      if (body.username == user_info.username && body.password == user_info.password) {
        //将登陆信息保存在session中
        req.session.user = user_info
        // 服务端重定向针对异步请求无效
        return res.json({
          //用户数据
          user: req.session.user,
          message: '登录成功',
          status: 200
        })
      } else {
        return res.json({
          status: 400,
          message: '登录失败，请检查账号或者密码！'
        })
      }
    }
  })
})

module.exports = router;
